const mongoose = require("mongoose");

const { host, port, database } = require("../config");
const dbURI = `mongodb://${host}:${port}/${database}`;

const connectWithRetry = () => {
	mongoose.connect(dbURI).then(() => {
		console.log("MongoDB连接成功");
	}).catch(error => {
		console.log(`MongoDB连接失败: ${error}`);
	});
};

// 设置回调
mongoose.connection.on("error", error => {
	console.error("MongoDB连接出现错误", error);
});

mongoose.connection.on("close", () => {
	console.log("MongoDB连接关闭");
});

// 应用程序结束关闭连接
const gracefulShutdown = (msg, callback) => {
	mongoose.connection.close(() => {
		console.log(`MongoDB disconnected through ${msg}`);
		callback();
	});
};

// 监听结束进程的情况
process.on("SIGINT", () => {
	gracefulShutdown("app termination", () => {
		process.exit(0);
	});
});
process.on("SIGTERM", () => {
	gracefulShutdown("Heroku app shutdown", () => {
		process.exit(0);
	});
});

// 开始连接
connectWithRetry();